package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendVideo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/2 0002 下午 7:04
 */

@DubboService
public class RecommendVideoApiImpl implements RecommendVideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<RecommendVideo> queryRecommendVideoList(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        return mongoTemplate.find(query,RecommendVideo.class);
    }

    @Override
    public List<RecommendVideo> RandomRecommendVideoList(Integer counts, Long userId) {
        TypedAggregation aggregation = Aggregation.newAggregation(RecommendVideo.class, Aggregation.sample(counts),Aggregation.match(Criteria.where("userId").nin(userId)));

        AggregationResults<RecommendVideo> aggregate = mongoTemplate.aggregate(aggregation, RecommendVideo.class);

        return aggregate.getMappedResults();
    }
}
